#!/bin/bash

## 部署 haproxy 用于进行负载分发

# 获取脚本路径
CURRENT_DIR=$(cd $(dirname $0); pwd)
# 导入公共方法
source ${CURRENT_DIR}/common.sh
# 导入配置文件
source ${CURRENT_DIR}/config.cnf


PATRONI_RESTAPI_PORT=8000
POSTGRESQL_PORT=${pg_port}





function install_haproxy(){
  local CHK_RESULT=$(rpm -qa|grep haproxy|wc -l)
  if [ $CHK_RESULT -eq 0 ];then
    comm_print_note "使用yum安装 Haproxy..."
    yum install -y haproxy
  else
    comm_print_error "haproxy 已被安装,请确认，若要共用请参考脚本自行配置postgres相关参数!"
    exit 1
  fi
}

function set_haproxy_postgres(){
  cat > /etc/haproxy/haproxy.cfg  << EOF
global
    maxconn 2000
 
defaults
    log    global
    mode    tcp
    retries 2
    timeout client 360m
    timeout connect 30s
    timeout server 360m
    timeout check 5s

listen stats
    mode http
    bind *:${haproxy_manager_port}
    stats enable
    stats uri /
 
listen primary
    bind *:${haproxy_postgres_primary_port}
    option httpchk OPTIONS /master
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
 
listen standbys
    balance roundrobin
    bind *:${haproxy_postgres_replica_port}
    option httpchk OPTIONS /replica
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
EOF

  local array=(${postgres_cluster_ip//,/ })
  for ip in "${array[@]}";do
    sed -i "/default-server/ a\    server ${ip} ${ip}:${pg_port} maxconn 2000 check port ${PATRONI_RESTAPI_PORT}" /etc/haproxy/haproxy.cfg
  done
}


function install(){
  comm_print_note "安装haproxy..."
  install_haproxy
  comm_print_note "设置haproxy相关的postgres配置如下：
   【
     haproxy_manager_port：${haproxy_manager_port}
     haproxy_postgres_primary_port：${haproxy_postgres_primary_port}
     haproxy_postgres_replica_port：${haproxy_postgres_replica_port} 
    】
  "
  set_haproxy_postgres   

  comm_print_note "启动haproxy..."
  systemctl start haproxy
  comm_print_note "设置haproxy为开机自启..."
  systemctl enable haproxy

  sleep 2

  local CHK_STATUS=$(systemctl status haproxy|grep 'active (running)'|wc -l)
  if [ $CHK_STATUS -eq 0 ];then
    comm_print_error "haproxy 启动失败，请检查!"
    exit 1
  fi
}

function uninstall(){
  comm_print_note "卸载haproxy..."
  local CHK_RESULT=$(rpm -qa|grep haproxy|wc -l)
  if [ $CHK_RESULT -gt 0 ];then
    yum remove haproxy -y
  fi
  comm_print_note "卸载haproxy完成."
}

function main(){
  if [ "$1" == "install" ];then
    install
  elif [ "$1" == "uninstall" ];then
    uninstall
  else
    comm_print_note "
	$0  install		安装postgres相关的haproxy
        $0  uninstall 		卸载haproxy
	"
  fi
}

main $1
